<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Users;
use App\Models\Linkslistsminapps;
use App\Models\Linkslists;
use App\Models\Miniappsauthorization;
use App\Models\Minappslists;
use App\Models\Miniappsbeian;
use App\Models\Templateadmin;
use App\Models\Templatebeian;
use App\Models\Miniappswxaauth;
use App\Services\WechatService;
use App\Services\WechatwqopenService;
use App\Services\WechatcheckService;
use App\Services\OutputService;
use App\Services\CacheService;
use App\Services\BaidusbService;
use App\Services\MiniappopenService;
use App\Services\WechaterrorService;
use App\Jobs\Miniappswitch;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use Auth,Config,Exception,Log;

class MiniappController extends Controller
{
    public function miniappList(Request $request)
    {
        $users = Auth::user();
        // 有权限认证
        $linkListMinapps = Linkslistsminapps::linkslistsminapps($users->id,$request->title,$request->type,$request->appid);
        $types = Linkslistsminapps::$types;
        $condition = $request->all();
        return view('admin.miniapp.bind.minapp_list',["linkListMinapps"=>$linkListMinapps,"condition"=>$condition,"types"=>$types]);
    }

    public function miniappBind(Request $request)
    {
        return view("admin.miniapp.bind.miniapp_bind");
    }

    public function minappAdd(Request $request)
    {
        return view('admin.miniapp.bind.minapp_add');
    }

    public function minappAddSubmit(Request $request)
    {
        if (empty($request->name)) return OutputService::error("请输入小程序名称！");
        if (empty($request->appid)) return OutputService::error("请输入小程序Appid！");
        if (empty($request->secret)) return OutputService::error("请输入小程序Secret！");
        if (empty($request->original_id)) return OutputService::error("请输入小程序原始ID！");
        if (strlen($request->appid) != 18 || substr($request->appid,0,2) != "wx") return OutputService::error("请输入正确的Appid");
        if (mb_strlen($request->name) > 35) return OutputService::error("小程序名称不能超过35位！");
        if (strlen($request->secret) != 32) return OutputService::error("请输入正确的AppSecret!");
        if (strlen($request->original_id) != 15 || substr($request->original_id,0,3) != "gh_") return OutputService::error("请输入正确的原始ID!");

        $minapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->appid);
        if (!empty($minapp)) return OutputService::error("小程序已存在,请不要重复添加！");
        $users = Auth::user();
        if ($users->authority != 3 && !empty($request->users_id)) return OutputService::error("参数错误,请稍后尝试！");
        // 验证密钥是否正确
        $appsecret_right = WechatService::appsecretRight($request->appid,$request->secret);
        // 密钥错误不能添加
        if ($appsecret_right["status"] == "error") return OutputService::error($appsecret_right["msg"]."如有疑问请联系客服！");
        $status = empty($request->status) ? 1 :$request->status;
        $users_id = empty($request->users_id) ? $users->id :$request->users_id;
        $type = empty($request->type) ? 1 :$request->type;
        $disable = empty($request->disable) ? 1 :$request->disable;
        $minappid = Linkslistsminapps::linksListsMinappsInsert($request->name,$request->appid,$request->secret,$users_id,$status,$disable,$request->original_id,$type,$request->scene);
        return OutputService::success("微信小程序添加成功！");
    }

    public function minappUpdate(Request $request,$appid)
    {
        $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
        if (empty($minapps)) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        $users = Auth::user();
        if ($users->authority != 3 && $minapps->disable == 4) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        if ($users->authority != 3 && $users->id != $minapps->users_id) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        return view('admin.miniapp.bind.minapp_update',['minapps'=>$minapps]);
    }

    public function minappUpdateSubmit(Request $request,$appid)
    {
        if (empty($request->name)) return back()->with("status","error")->with("msg","请输入小程序名称！");
        if (empty($request->appid)) return back()->with("status","error")->with("msg","请输入小程序Appid！");
        if (empty($request->original_id)) return back()->with("status","error")->with("msg","请输入小程序原始ID！");
        if (strlen($request->appid) != 18 || substr($request->appid,0,2) != "wx") return back()->with("status","error")->with("msg","请输入正确的Appid");
        if (strlen($request->original_id) != 15 || substr($request->original_id,0,3) != "gh_") return back()->with("status","error")->with("msg","请输入正确的原始ID!");

        $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
        if ($minapps->miniapp_type == 2 && empty($request->secret)) return back()->with("status","error")->with("msg","请输入小程序Secret！");
        if ($minapps->miniapp_type == 2 && strlen($request->secret) != 32) return back()->with("status","error")->with("msg","请输入正确的AppSecret!");
        $status = empty($request->status) ? $minapps->status :$request->status;
        $users_id = empty($request->users_id) ? $minapps->users_id :$request->users_id;
        $type = empty($request->type) ? $minapps->type :$request->type;
        $miniapp_type = empty($request->miniapp_type) ? $minapps->miniapp_type :$request->miniapp_type;

        // 更新了小程序类型,批量切换
        if (!empty($request->miniapp_type) && $minapps->miniapp_type != $miniapp_type) {
            Linkslists::updateLinksMiniappType($request->appid,$miniapp_type);
            $msg = "小程序更新成功,请批量替换小程序旗下链接。";
        } else {
            $msg = "小程序更新成功。";
        }

        if (empty($minapps)) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapps->users_id) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");     
        if ($users->authority != 3 && $minapps->disable == 4) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");   
        Linkslistsminapps::linksListsMinappsAppUpdate($minapps->id,$request->name,$request->appid,$request->secret,$users_id,$status,$request->disable,$request->original_id,$type,$miniapp_type,$request->scene);
        CacheService::miniappCacheRemove($request->appid);
        return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg",$msg);
    }

    public function minappDisable(Request $request,$appid)
    {
        $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
        if (empty($minapps)) return back()->with("status","error")->with("msg","小程序不存在！");
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapps->users_id) return back()->with("status","error")->with("msg","小程序不存在！");
        if ($users->authority != 3 && $minapps->disable == 4) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        $disable = $minapps->disable == 2 ? 1 : 2;
        Linkslistsminapps::updateLinksListsStatus($minapps->id,$disable);
        if ($minapps->status == 1) {
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序禁用成功！");
        } else {
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序禁用成功,请前往切换公用小程序链接。");
        }
    }

    public function minappDelete(Request $request)
    {
        $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($request->appid);
        if (empty($minapps)) return OutputService::error("小程序不存在！");
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapps->users_id) return OutputService::error("小程序不存在！");
        if ($users->authority != 3 && $minapps->disable == 4) return OutputService::error("小程序不存在！");
        $linksList = Linkslists::getLinksIdByAppid($request->appid);
        if (!empty($linksList)) return OutputService::error("小程序使用中,您可以删除或者更新链接的小程序后再操作！外链ID：".$linksList->links_id);
        Linkslistsminapps::deleteLinksListsMinapps($minapps->id);
        Miniappsauthorization::miniappAuthorizationDelete($request->appid);
        return OutputService::success("微信小程序删除成功!");
    }

    public function minappDefault(Request $request,$appid)
    {
        $minapps = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
        if (empty($minapps)) return back()->with("status","error")->with("msg","小程序不存在！");
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapps->users_id) return back()->with("status","error")->with("msg","小程序不存在！");
        if ($users->authority != 3 && $minapps->disable == 4) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序不存在！");
        $disable = $minapps->disable == 3 ? 1 : 3;
        Linkslistsminapps::updateLinksListsStatus($minapps->id,$disable);
        if ($minapps->status == 1) {
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序设置为默认成功,请前往修改自己的链接！");
        } else {
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序设置为默认成功,请前往切换公用小程序链接。");
        }
    }

    public function minappScene(Request $request,$id)
    {
        if (empty($id)) return response()->json(["status"=>"error","code"=>"1001","msg"=>"接口异常,请稍后重试！"]);
        $minapps = Linkslistsminapps::getLinksListsMinappsById($id);
        if ($minapps->scene == 1) {
            Linkslistsminapps::updateMiniappScene($id,2);
            return response()->json(["status"=>"success","code"=>"1002","msg"=>"开启监听成功！"]);
        } else {
            Linkslistsminapps::updateMiniappScene($id,1);
            return response()->json(["status"=>"success","code"=>"1003","msg"=>"关闭监听成功！"]);
        }
    }

    public function miniappsChange(Request $request)
    {
        $users = Auth::user();
        $miniapps = Linkslistsminapps::getUsersUseableMinapps($users->id);
        return view('admin.links_lists.links_lists_miniapps_change',['miniapps'=>$miniapps]);
    }

    public function miniappsChangeSubmit(Request $request)
    {
        $users = Auth::user();
        if (empty($request->oldappid)) return back()->with("status","error")->with("msg","请选择旧的微信小程序！");
        if (empty($request->appid)) return back()->with("status","error")->with("msg","请输入新的微信小程序！");
        if ($request->oldappid == $request->appid) return back()->with("status","error")->with("msg","旧的小程序和新的小程序相同，无法切换！");
        $oldminiapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->oldappid);
        if (empty($oldminiapp)) return back()->with("status","error")->with("msg","旧的小程序不存在!");
        if ($oldminiapp->users_id != $users->id) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $miniapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->appid);
        if (empty($miniapp)) return back()->with("status","error")->with("msg","新的小程序不存在!");
        if ($miniapp->users_id != $users->id) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        Miniappswitch::dispatch($request->oldappid,"",$users->id,$request->appid)->delay(1);
        return redirect("/admin/links_lists/links_lists_miniapps_change")->with("status","success")->with("msg","提交成功,10S后开始批量切换链接使用的小程序！");
    }

    public function miniappBindScan(Request $request)
    {
        try {
            // 获取预授权码
            $scanMini = Config::get("wechats.open_platform.wqurlscheme");
            $preAuthcode = WechatwqopenService::apiCreatePreauthcode($scanMini["app_id"]);
            if (!isset($preAuthcode["pre_auth_code"])) {
                if ($preAuthcode["errcode"] == 61004) return OutputService::error("系统IP异常,请联系客服为您处理！");
            }
            $pre_auth_code = $preAuthcode["pre_auth_code"];
        } catch (Exception $e) {
            $pre_auth_code = "";
        }
        $config = Config::get("wechats.open_platform.wqurlscheme");
        $component_appid = $config["app_id"];
        // 前往授权得到授权码
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=".$component_appid."&pre_auth_code=".$pre_auth_code."&redirect_uri=https://bab.moreqifu.cn/admin/miniapp/miniapp_bind_scan_back&auth_type=3";
        return OutputService::success("SUCCESS",["url"=>$url]);
    }

    public function miniappBindScanBack(Request $request)
    {
        try {            
            // 授权码
            $authorization_code = $request->auth_code;
            // 使用授权码获取授权信息
            $apiQueryAuth = WechatwqopenService::apiQueryAuth($authorization_code);
            if (isset($apiQueryAuth["errcode"])) {
                if ($apiQueryAuth["errcode"] == 61010) return redirect("/admin/miniapp/miniapp_bind")->with("status","error")->with("msg","授权码已过期,请重新授权！");
                if ($apiQueryAuth["errcode"] == 50002) return redirect("/admin/miniapp/miniapp_bind")->with("status","error")->with("msg","公众号/小程序已被封禁或冻结,请重新授权！");
            }
            $config = Config::get("wechats.open_platform.wqurlscheme");
            $component_appid = $config["app_id"];
            $appid = $apiQueryAuth["authorization_info"]["authorizer_appid"];
            $lastMiniappAuthor = Miniappsauthorization::getLastMiniappAuthorization($appid);
            if (!empty($lastMiniappAuthor)) {
                if ($component_appid != $lastMiniappAuthor->component_appid) {
                    return redirect("/admin/miniapp/miniapp_bind")->with("status","error")->with("msg","您的小程序已绑定过天天外链，请勿重复绑定；如果是后台上架的小程序上架成功后会自动同步到小程序列表！");
                } else {
                    Miniappsauthorization::insertOpenToken($component_appid,$appid,$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],time(),$authorization_code,1,time(),$apiQueryAuth["authorization_info"]["authorizer_access_token"],$apiQueryAuth["authorization_info"]["expires_in"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],2);
                    return redirect("/admin/miniapp/miniapp_bind")->with("status","error")->with("msg","您的小程序已绑定过天天外链，请勿重复绑定；如有疑问请联系客服处理!");
                }
            }

            Miniappsauthorization::insertOpenToken($component_appid,$appid,$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],time(),$authorization_code,1,time(),$apiQueryAuth["authorization_info"]["authorizer_access_token"],$apiQueryAuth["authorization_info"]["expires_in"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],2);

            // 获取授权方的帐号基本信息
            $apiGetAuthorizerInfo = WechatwqopenService::apiGetAuthorizerInfo($appid);

            $original_id = $apiGetAuthorizerInfo["authorizer_info"]["user_name"];
            $users_id = Auth::user()->id;
            $appid = $appid;
            $name = $apiGetAuthorizerInfo["authorizer_info"]["nick_name"];
            // 判断小程序是否存在
            $linksListsMinapp = Linkslistsminapps::getLinksListsMinappsByAppid($appid);
            if (empty($linksListsMinapp)) {
                // 添加小程序数据
                Linkslistsminapps::authLinksListsMinappsInsert($name,$appid,$users_id,$original_id);
            } else {
                // 将小程序更新信息并且绑定为当前用户
                Linkslistsminapps::authLinksListsMinappsUpdate($linksListsMinapp->id,$name,$appid,$original_id,$users_id);
            }
            Cache::forget('links_token_'.$appid);
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序授权成功,去创建链接吧！");
        } catch (Exception $e) {
            Log::info("selfMiniappBindBack-----");
            Log::info($request->all());
            Log::info($e);
            Log::info($apiQueryAuth);
            Log::info($apiGetAuthorizerInfo);
            Log::info("selfMiniappBindBack-----");
        }
    }

    public function miniappCheckBind(Request $request)
    {
        if (empty($request->appid)) return OutputService::error("参数错误,请稍后尝试!");
        $users = Auth::user();
        $linkMiniapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->appid);
        if (empty($linkMiniapp)) return OutputService::error("小程序不存在!");
        if ($linkMiniapp->disable == 2) return OutputService::error("小程序不存在或已禁用!");
        if ($linkMiniapp->users_id != $users->id && $users->authority < 3) return OutputService::error("小程序不存在!");
        if ($linkMiniapp->visitstatus == 1 && $request->visit_status == 1) return OutputService::error("您已开启了检测,请勿重复操作!");
        if ($request->visit_status == 1) {
            $checkMini = Config::get("wechats.open_platform.checkmini");
            $miniAuthor = Miniappsauthorization::getCompMiniappAuth($request->appid,$checkMini["app_id"]);
            // 如果有授权记录且未取消授权
            if (!empty($miniAuthor) && $miniAuthor->status != 2) {
                Linkslistsminapps::updateLinkListMiniappVisit($linkMiniapp->id,1);
                return OutputService::success("检测状态开启成功!",["url"=>""]);
            }
            try {
                // 获取预授权码
                $preAuthcode = WechatcheckService::apiCreatePreauthcode();
                if (!isset($preAuthcode["pre_auth_code"])) {
                    if ($preAuthcode["errcode"] == 61004) return OutputService::error("系统IP异常,请联系客服为您处理！");
                }
                $pre_auth_code = $preAuthcode["pre_auth_code"];
            } catch (Exception $e) {
                return OutputService::error("请求失败,请稍后尝试!");
            }
            $checkMini = Config::get("wechats.open_platform.checkmini");
            // 前往授权得到授权码
            $bindurl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=".$checkMini["app_id"]."&pre_auth_code=".$pre_auth_code."&redirect_uri=https://bab.moreqifu.cn/admin/miniapp/miniapp_check_bind_back/".$request->appid."&auth_type=3";
            return OutputService::success("SUCCESS",["url"=>$bindurl]);
        } else {
            Linkslistsminapps::updateLinkListMiniappVisit($linkMiniapp->id,5);
            return OutputService::success("检测状态关闭成功!");
        }
    }

    public function miniappCheckBindBack(Request $request,$appid)
    {
        try {            
            // 授权码
            $authorization_code = $request->auth_code;
            // 使用授权码获取授权信息
            $apiQueryAuth = WechatcheckService::apiQueryAuth($authorization_code);
            if (isset($apiQueryAuth["errcode"])) {
                if ($apiQueryAuth["errcode"] == 61010) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","授权码已过期,请重新授权！");
                if ($apiQueryAuth["errcode"] == 50002) return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","公众号/小程序已被封禁或冻结,请重新授权！");
            }

            $config = Config::get("wechats.open_platform.checkmini");
            $component_appid = $config["app_id"];

            Miniappsauthorization::insertOpenToken($component_appid,$apiQueryAuth["authorization_info"]["authorizer_appid"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],time(),$authorization_code,1,time(),$apiQueryAuth["authorization_info"]["authorizer_access_token"],$apiQueryAuth["authorization_info"]["expires_in"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],3);
            // 开启小程序检测状态
            Linkslistsminapps::updateLinkListMiniappVisitAppid($apiQueryAuth["authorization_info"]["authorizer_appid"],1);
            return redirect("/admin/miniapp/miniapp_list")->with("status","success")->with("msg","小程序状态检测开启成功!");
        } catch (Exception $e) {
            return redirect("/admin/miniapp/miniapp_list")->with("status","error")->with("msg","小程序状态检测开启失败,请联系客服处理!");
        }
    }

    public function minappChange(Request $request)
    {
        $users = Auth::user();
        $miniapps = Linkslistsminapps::getUsersUseableMinapps($users->id);
        return view('admin.miniapp.link.minapp_change',['miniapps'=>$miniapps]);
    }

    public function minappChangeSubmit(Request $request)
    {
        $users = Auth::user();
        if (empty($request->oldappid)) return back()->with("status","error")->with("msg","请选择旧的微信小程序！");
        if (empty($request->appid)) return back()->with("status","error")->with("msg","请输入新的微信小程序！");
        if ($request->oldappid == $request->appid) return back()->with("status","error")->with("msg","旧的小程序和新的小程序相同，无法切换！");
        $oldminiapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->oldappid);
        if (empty($oldminiapp)) return back()->with("status","error")->with("msg","旧的小程序不存在!");
        if ($oldminiapp->users_id != $users->id) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $miniapp = Linkslistsminapps::getLinksListsMinappsByAppid($request->appid);
        if (empty($miniapp)) return back()->with("status","error")->with("msg","新的小程序不存在!");
        if ($miniapp->users_id != $users->id) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        Miniappswitch::dispatch($request->oldappid,"",$users->id,$request->appid)->delay(1);
        return redirect("/admin/miniapp/minapp_change")->with("status","success")->with("msg","提交成功,3秒后后开始批量切换链接使用的小程序！");
    }

    public function miniappBeian(Request $request)
    {
        $users = Auth::user();
        $users_id = $users->id;
        $templateBeians = Templatebeian::templateBeianListName($users_id);
        $templateAdmins = Templateadmin::userTemplateAdmin($users_id);
        $minappLists = Minappslists::userBeianMiniappLists($users_id);
        return view("admin.miniapp.beian.miniapp_beian",["templateBeians"=>$templateBeians,"templateAdmins"=>$templateAdmins,"minappLists"=>$minappLists]);
    }

    public function miniappBeianResult(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapp->users_id) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","小程序不存在！");
        $icpEntranceInfo = MiniappopenService::getIcpEntranceInfo($minapp->appid_third,$appid);
        // Log::info($icpEntranceInfo);
        if ($icpEntranceInfo["errcode"] == 0) {
            if ($icpEntranceInfo["info"]["status"] == 6) {
                // 已经完成备案,
                Minappslists::updateBeianStatus($appid,2);
                $miniappBeian = Miniappsbeian::getMiniappBeian($appid);
                $beianInfo = $miniappBeian->beian_info;
            }
            return view("admin.miniapp.beian.miniapp_beian_status",["appid"=>$appid,"icpEntranceInfo"=>$icpEntranceInfo["info"],"status"=>"success"]);
        } else {
            $message = WechaterrorService::getErrorMessage($icpEntranceInfo["errcode"]);
            return view("admin.miniapp.beian.miniapp_beian_status",["appid"=>$appid,"status"=>"error","message"=>$message]);
        }
    }

    public function miniappBeianImage(Request $request)
    {
        $users = Auth::user();
        if (in_array($request->status, ["legal_photo_front","manage_photo_front"])) {
            $idcardResult = BaidusbService::idcardOcr($request->imgurl,"front");
            if ($idcardResult["image_status"] != "normal") {
                return OutputService::error("请上传清晰的身份证正面照!");
            }
            $name = $idcardResult["words_result"]["姓名"]["words"];
            $idcard = $idcardResult["words_result"]["公民身份号码"]["words"];

            if ($request->status == "legal_photo_front") {
                $certificate_type = "icp_subject.principal_info.certificate_photo_front";
            } else {
                $certificate_type = "icp_applets.principal_info.certificate_photo_front";
            }
            return OutputService::success("SUCCESS",["name"=>$name,"idcard"=>$idcard]);
        } elseif (in_array($request->status, ["legal_photo_back","manage_photo_back"])) {
            $idcardResult = BaidusbService::idcardOcr($request->imgurl,"back");
            if ($idcardResult["image_status"] != "normal") {
                return OutputService::error("请上传清晰的身份证反面照!");
            }
            $date_end = $idcardResult["words_result"]["失效日期"]["words"];
            $date_start = $idcardResult["words_result"]["签发日期"]["words"];

            if ($request->status == "legal_photo_front") {
                $certificate_type = "icp_subject.principal_info.certificate_photo_back";
            } else {
                $certificate_type = "icp_applets.principal_info.certificate_photo_back";
            }
            return OutputService::success("SUCCESS",["date_start"=>$date_start,"date_end"=>$date_end]);
        } elseif($request->status == "license"){
            $licenseResult = BaidusbService::licenseOcr($request->imgurl);
            if (isset($licenseResult["error_code"])) {
                if ($licenseResult["error_code"] == 282103) return OutputService::error("请上传正确的营业执照!");
            }
            $uploadResult = ["certificate_name"=>$licenseResult["words_result"]["单位名称"]["words"],"certificate_address"=>$licenseResult["words_result"]["地址"]["words"],"certificate_number"=>$licenseResult["words_result"]["社会信用代码"]["words"],"legal_person"=>$licenseResult["words_result"]["法人"]["words"]];
            return OutputService::success("SUCCESS",$uploadResult);
        } elseif($request->status == "authorization_letter"){
            $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_applets.principal_info.authorization_letter",$request->imgurl);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            }
            $uploadResult = ["media_id"=>$uploadInfo["media_id"]];
            return OutputService::success("SUCCESS",$uploadResult);
        } elseif($request->status == "commitment_letter"){
            $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_materials.commitment_letter",$request->imgurl);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            }
            $uploadResult = ["media_id"=>$uploadInfo["media_id"]];
            return OutputService::success("SUCCESS",$uploadResult);
        }
    }

    public function miniappBeianVerify(Request $request)
    {
        $appid = $request->appid;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapp->users_id) return OutputService::error("您无权执行本操作!");
        if (empty($appid)) return OutputService::error("参数错误!");
        //是否已经创建，创建的话三天有效
        $verifyTask = Cache::remember('verify_task_'.$appid, 259200, function () use ($appid) {
            $verifyTask = MiniappopenService::createIcpVerifyTask($appid);
            if ($verifyTask["errcode"] == 40001) {
                Redis::del("miniapp_access_token_".$appid);
                $verifyTask = MiniappopenService::createIcpVerifyTask($appid);
            }
            return $verifyTask;
        });
        Log::info($verifyTask);
        if($verifyTask["errcode"] != 0){
            Cache::forget('verify_task_'.$appid);
            $message = WechaterrorService::getErrorMessage($verifyTask["errcode"]);
            return OutputService::error($message);
        }
        if(isset($verifyTask['task_id'])){
            $verifyTasks = MiniappopenService::queryIcpVerifyTask($appid,$verifyTask['task_id']);
            $verifyTasks['task_id'] = $verifyTask['task_id'];
        }
        return OutputService::success($verifyTasks);
    }

    public function miniappBeianVerifyCheck(Request $request)
    {
        $appid = $request->appid;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users = Auth::user();
        if ($users->authority != 3 && $users->id != $minapp->users_id) return OutputService::error("您无权执行本操作!");
        $task_id = $request->task_id;
        if (empty($appid)) return OutputService::error("参数错误!");
        if (empty($task_id)) return OutputService::error("参数错误!");
        $verifyTask = MiniappopenService::queryIcpVerifyTask($appid,$task_id);
        return OutputService::success("SUCCESS",$verifyTask);
    }

    public function miniappBeianSubmit(Request $request)
    {
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        if (empty($request->admin_id)) return OutputService::error("参数错误!");
        if (empty($request->appid)) return OutputService::error("请选择备案的微信小程序!");
        if (empty($request->comment)) return OutputService::error("请输入小程序简介!");
        $appid = $request->appid;
        $templateBeian = Templatebeian::templateBeianDetial($request->corp_id);
        $templateAdmin = Templateadmin::templateAdminDetial($request->admin_id);
        $beianInfo = json_decode($templateBeian->beian_info,true);

        // 上传营业执照
        $uploadInfo = MiniappopenService::uploadIcpMedia($appid,1,"icp_subject.organize_info.certificate_photo",$beianInfo["icp_subject"]["organize_info"]["certificate_image"]);
        if ($uploadInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            return OutputService::error($message);
        } else {
            $beianInfo["icp_subject"]["organize_info"]["certificate_photo"] = $uploadInfo["media_id"];
        }

        // 负责人正面
        $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_subject.principal_info.certificate_photo_front",$beianInfo["icp_subject"]["principal_info"]["certificate_photo_front_img"]);
        if ($uploadInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            return OutputService::error($message);
        } else {
            $beianInfo["icp_subject"]["principal_info"]["certificate_photo_front"] = $uploadInfo["media_id"];
        }

        // 负责人反面
        $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_subject.principal_info.certificate_photo_back",$beianInfo["icp_subject"]["principal_info"]["certificate_photo_back_img"]);
        if ($uploadInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            return OutputService::error($message);
        } else {
            $beianInfo["icp_subject"]["principal_info"]["certificate_photo_back"] = $uploadInfo["media_id"];
        }

        $beianInfo["icp_applets"] = ["base_info"=>["service_content_types"=>[3],"nrlx_details"=>[["type"=>24]],"comment"=>$request->comment],"principal_info"=>["name"=>$templateAdmin->manage_name,"mobile"=>$templateAdmin->manage_mobile,"email"=>$templateAdmin->manage_email,"emergency_contact"=>$templateAdmin->manage_emergency_contact,"certificate_type"=>2,"certificate_number"=>$templateAdmin->manage_idcard,"certificate_validity_date_start"=>$templateAdmin->manage_date_start,"certificate_validity_date_end"=>$templateAdmin->manage_date_end,"certificate_photo_front_img"=>$templateAdmin->manage_photo_front,"certificate_photo_back_img"=>$templateAdmin->manage_photo_back,"authorization_letter_back_img"=>$request->authorization_letter_back_img]];

        // 管理员正面
        $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_applets.principal_info.certificate_photo_front",$beianInfo["icp_applets"]["principal_info"]["certificate_photo_front_img"]);
        if ($uploadInfo["errcode"] != 0) {
            dump(4);
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            return OutputService::error($message);
        } else {
            $beianInfo["icp_applets"]["principal_info"]["certificate_photo_front"] = $uploadInfo["media_id"];
        }

        // 管理员反面
        $uploadInfo = MiniappopenService::uploadIcpMedia($appid,2,"icp_applets.principal_info.certificate_photo_back",$beianInfo["icp_applets"]["principal_info"]["certificate_photo_back_img"]);
        if ($uploadInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            dump(5);
            return OutputService::error($message);
        } else {
            $beianInfo["icp_applets"]["principal_info"]["certificate_photo_back"] = $uploadInfo["media_id"];
        }

        if (!empty($beianInfo["icp_subject"]["principal_info"]["authorization_letter_back_img"])) {
            // 判断是否需要上传授权书
            $uploadInfo = MiniappopenService::uploadIcpMedia($appid,1,"icp_subject.principal_info.authorization_letter",$beianInfo["icp_subject"]["principal_info"]["authorization_letter"]);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            } else {
                $beianInfo["icp_subject"]["principal_info"]["authorization_letter"] = $uploadInfo["media_id"];
            }
        }

        //小程序管理员是否需要授权书
        if(!empty($request->shqshUrl)){
            // 判断是否需要上传授权书
            $uploadInfo = MiniappopenService::uploadIcpMedia($appid,1,"icp_applets.principal_info.authorization_letter",$request->shqshUrl);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            } else {
                $beianInfo["icp_applets"]["principal_info"]["authorization_letter"] = $uploadInfo["media_id"];
            }
        }

        //小程序其他附件
        if(!empty($request->applets_other_materials_url)){
            // 判断是否需要上传授权书
            $uploadInfo = MiniappopenService::uploadIcpMedia($appid,1,"icp_materials.applets_other_materials",$request->applets_other_materials_url);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            } else {
                $beianInfo["icp_materials"]["applets_other_materials"] = $uploadInfo["media_id"];
            }
        }

        //扫脸任务task_id
        $beianInfo["icp_applets"]["principal_info"]["verify_task_id"] = $request->verify_task;
 
        $miniappBeian = Miniappsbeian::getMiniappBeian($appid);
        if (empty($miniappBeian)) {
            Miniappsbeian::insertMiniappBeian($appid,json_encode($beianInfo));
        } else {
            Miniappsbeian::updateMiniappBeian($appid,json_encode($beianInfo));
        }
        unset($beianInfo["icp_subject"]["organize_info"]["certificate_image"]);
        unset($beianInfo["icp_subject"]["principal_info"]["certificate_photo_front_img"]);
        unset($beianInfo["icp_subject"]["principal_info"]["certificate_photo_back_img"]);
        unset($beianInfo["icp_subject"]["principal_info"]["authorization_letter_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["certificate_photo_front_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["certificate_photo_back_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["authorization_letter_back_img"]);
        unset($beianInfo["icp_materials"]["commitment_letter_back_img"]);

        if(empty($beianInfo["icp_applets"]["principal_info"]["authorization_letter"])) unset($beianInfo["icp_applets"]["principal_info"]["authorization_letter"]);
        if(empty($beianInfo["icp_subject"]["principal_info"]["authorization_letter"])) unset($beianInfo["icp_subject"]["principal_info"]["authorization_letter"]);
        if(empty($beianInfo["icp_materials"]["commitment_letter"])) unset($beianInfo["icp_materials"]["commitment_letter"]);
        // Log::info($beianInfo);
        $filingResult = MiniappopenService::applyIcpFiling($request->appid,$beianInfo);
        Log::info($filingResult);
        if ($filingResult["errcode"] == 0) {
            return OutputService::success("备案提交成功，等待腾讯初审");
        } else {
            if ($filingResult["errcode"] == 86202) {
                if($filingResult["hints"][0]["err_field"] == 'icp_applets.principal_info.verify_task_id'){
                    Cache::forget('verify_task_'.$appid);
                }
                return OutputService::error("申请小程序备案失败，请根据返回的错误提示进行修改；",$filingResult["hints"]);
            }
            if ($filingResult["errcode"] == 86301) return OutputService::error("系统错误，请稍后重试");
            if ($filingResult["errcode"] == 86302) return OutputService::error("输入信息与图片信息相差过大,重新拍摄上传图片");
            if ($filingResult["errcode"] == 86303) return OutputService::error("无法获取号码归属地,请重试或更换一个号码");
            if ($filingResult["errcode"] == 86308) return OutputService::error("证件有效期不满足要求,请确保证件在有效期内，且有效期大于3个月");
            if ($filingResult["errcode"] == 86324) return OutputService::error("当前正在审核中，请勿重复提交");
            if ($filingResult["errcode"] == 86358) return OutputService::error("存在订单尚未完成，不允许再次提交");
            if ($filingResult["errcode"] == 47001) return OutputService::error("未知错误，请联系客服为您处理！");
        }
    }

    public function miniappBeianSubmit1(Request $request)
    {
        if (empty($request->corp_id)) return OutputService::error("参数错误!");
        if (empty($request->admin_id)) return OutputService::error("参数错误!");
        if (empty($request->miniappLists)) return OutputService::error("请选择备案的微信小程序!");

        $users = Auth::user();
        $users_id = $users->id;
        $miniappBeian = Miniappsbeian::getMiniappBeian($request->appid);
        if (empty($miniappBeian)) {
            Miniappsbeian::insertMiniappBeian($request->appid,$request->beianInfo);
        } else {
            Miniappsbeian::updateMiniappBeian($request->appid,$request->beianInfo);
        }
        $beianInfo = json_decode($request->beianInfo,true);
        unset($beianInfo["icp_subject"]["organize_info"]["certificate_image"]);
        unset($beianInfo["icp_subject"]["principal_info"]["certificate_photo_front_img"]);
        unset($beianInfo["icp_subject"]["principal_info"]["certificate_photo_back_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["certificate_photo_front_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["certificate_photo_back_img"]);
        unset($beianInfo["icp_applets"]["principal_info"]["authorization_letter_back_img"]);
        unset($beianInfo["icp_materials"]["commitment_letter_back_img"]);
        if(empty($beianInfo["icp_applets"]["principal_info"]["authorization_letter"])) unset($beianInfo["icp_applets"]["principal_info"]["authorization_letter"]);
        if(empty($beianInfo["icp_subject"]["principal_info"]["authorization_letter"])) unset($beianInfo["icp_subject"]["principal_info"]["authorization_letter"]);
        if(empty($beianInfo["icp_subject"]["principal_info"]["authorization_letter_back_img"])) unset($beianInfo["icp_subject"]["principal_info"]["authorization_letter_back_img"]);
        $filingResult = MiniappopenService::applyIcpFiling($request->appid,$beianInfo);
        Log::info($filingResult);
        if ($filingResult["errcode"] == 0) {
            return OutputService::success("SUCCESS");
        } else {
            if ($filingResult["errcode"] == 86202) {
                return OutputService::error("申请小程序备案失败，请根据返回的错误提示进行修改；",$filingResult["hints"]);
            }
            if ($filingResult["errcode"] == 86301) return OutputService::error("系统错误，请稍后重试");
            if ($filingResult["errcode"] == 86302) return OutputService::error("输入信息与图片信息相差过大,重新拍摄上传图片");
            if ($filingResult["errcode"] == 86303) return OutputService::error("无法获取号码归属地,请重试或更换一个号码");
            if ($filingResult["errcode"] == 86308) return OutputService::error("证件有效期不满足要求,请确保证件在有效期内，且有效期大于3个月");
            if ($filingResult["errcode"] == 86324) return OutputService::error("当前正在审核中，请勿重复提交");
            if ($filingResult["errcode"] == 86358) return OutputService::error("存在订单尚未完成，不允许再次提交");
            if ($filingResult["errcode"] == 47001) return OutputService::error("未知错误，请联系客服为您处理！");
        }
    }

    public function miniRemark(Request $request)
    {
        $users = $request->user();
        $times = Minappslists::updateMinappsListsRemark($users->id,$request->appid,$request->remark);
        if($times==0) return OutputService::error("备注更新失败");
        return OutputService::success("备注更新成功");
    }

    public function miniappService(Request $request)
    {
        $status = empty($request->status) ? 3 : $request->status;
        $qrcodes = [
            [],
            [["name"=>"王芸","qrcode"=>"https://res.wailian1.cn/miniapp/links/20230706/3d821eb5ef6581544b2022b747aa62e2.jpg"]],
            [["name"=>"李菲","qrcode"=>"https://res.wailian1.cn/miniapp/links/20230706/3d821eb5ef6581544b2022b747aa62e2.jpg"]],
            [["name"=>"李菲","qrcode"=>"https://res.wailian1.cn/miniapp/links/20230706/3d821eb5ef6581544b2022b747aa62e2.jpg"]],
        ];
        $qrcode = $qrcodes[$status];
        $service = $qrcode[rand(0,count($qrcode)-1)];
        return view("admin.index.service",["service"=>$service,"status"=>$status]);
    }

    public function miniappLast(Request $request)
    {
        $users = Auth::user();
        $minapp = Minappslists::getUserLastMiniList($users->id);
        if (empty($minapp)) {
            return OutputService::error("当前暂无备案中的小程序!");
        } else {
            return OutputService::success("SUCCESS",["appid"=>$minapp->appid]);
        }
    }

    public function wxaAuthSubmit(Request $request)
    {
        $appid = $request->appid;
        $authInfo = $request->authInfo;
        if (empty($appid)) return OutputService::error("请选择认证的微信小程序!");
        $miniapp = Minappslists::getMiniListsListsByAppid($appid);
        if(empty($miniapp)){
            return OutputService::error("小程序信息不存在，请重新选择小程序！");
        }
        // 上传营业执照
        $uploadInfo = MiniappopenService::uploadAuthMaterial($appid,$request->authInfo['qualification_image']);
        if ($uploadInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
            return OutputService::error($message);
        } else {
            $authInfo["qualification"] = $uploadInfo["mediaid"];
        }
        if(!empty($authInfo['qualification_other_image']) && $authInfo['qualification_other_image'][0]){
            $uploadInfo = MiniappopenService::uploadAuthMaterial($appid,$authInfo['qualification_other_image'][0]);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            } else {
                $authInfo["qualification_other"] = [$uploadInfo["mediaid"]];
            }
        }
        if(!empty($authInfo['account_supplemental_image']) && $authInfo['account_supplemental_image'][0] != null){
            $uploadInfo = MiniappopenService::uploadAuthMaterial($appid,$request->authInfo['account_supplemental_image'][0]);
            if ($uploadInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($uploadInfo["errcode"]);
                return OutputService::error($message);
            } else {
                $authInfo["account_supplemental"] = [$uploadInfo["mediaid"]];
            }
        }
        $authInfo['pay_type'] = 1;
        $authInfo['third_party_phone'] = '15658606443';
        $authInfo['service_appid'] = 'wxaea50bbedca28905';
        $authInfo['invoice_info']['invoice_type'] = 1;
        //查询是否认证，找taskid
        $taskid = '';
        $authResult = Miniappswxaauth::getMiniappsAuth($appid);
        if (!empty($authResult)) {
            $taskid = $authResult->taskid;
        } 
        $authInfo['taskid'] = $taskid;
        unset($authInfo["qualification_other_image"]);
        unset($authInfo["qualification_image"]);
        unset($authInfo["account_supplemental_image"]);

        if(empty($authInfo["qualification_other"])) unset($authInfo["qualification_other"]);
        if(empty($authInfo["qualification_other"])) unset($authInfo["qualification_other"]);
        if(empty($authInfo["account_supplemental"]) && $authInfo["account_name_type"] == 2) return OutputService::error("基于商标命名必须补充商标材料！");
        if(empty($authInfo["account_supplemental"])) unset($authInfo["account_supplemental"]);
        if(empty($authInfo['taskid'])) {
            $filingResult = MiniappopenService::wxaAuth($appid,$authInfo);
        }else{
            $filingResult = MiniappopenService::reAuth($appid,$authInfo);
        }
        // $filingResult = MiniappopenService::wxaAuth($appid,$authInfo);
        Log::info($filingResult);
        if ($filingResult["errcode"] == 0 && empty($authInfo['taskid'])) {
            //插入数据库
            Miniappswxaauth::insertAuth($appid,json_encode($authInfo),$filingResult["taskid"],2,0);
            return OutputService::success("认证提交成功，等待腾讯审核");
        } 
    }

}